package versions

import (
	"encoding/json"
	"github.com/pkg/errors"
	"os"
	"path/filepath"
	clitypes "xemo.top/docker/cli/types"
)

const (
	// defaultRuntimeMetadataDir is the location where the metadata file is stored
	defaultRuntimeMetadataDir = "/var/lib/docker-engine"
)

// GetCurrentRuntimeMetadata 从本地主机加载当前守护进程运行时元数据信息
// GetCurrentRuntimeMetadata loads the current daemon runtime metadata information from the local host
func GetCurrentRuntimeMetadata(metadataDir string) (*clitypes.RuntimeMetadata, error) {
	if metadataDir == "" {
		metadataDir = defaultRuntimeMetadataDir
	}
	filename := filepath.Join(metadataDir, clitypes.RuntimeMetadataName+".json")
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	var res clitypes.RuntimeMetadata
	err = json.Unmarshal(data, &res)
	if err != nil {
		return nil, errors.Wrapf(err, "malformed runtime metadata file %s", filename)
	}
	return &res, nil
}

// WriteRuntimeMetadata stores the metadata on the local system
func WriteRuntimeMetadata(metadataDir string, metadata *clitypes.RuntimeMetadata) error {
	if metadataDir == "" {
		metadataDir = defaultRuntimeMetadataDir
	}
	filename := filepath.Join(metadataDir, clitypes.RuntimeMetadataName+".json")

	data, err := json.Marshal(metadata)
	if err != nil {
		return err
	}

	os.Remove(filename)
	return os.WriteFile(filename, data, 0644)
}
